package com.example.springmvc.common;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.List;

/**
 * 统一接口响应结构
 *
 * @author fanhang
 */
public class WebResult<T> {
    /**
     * 状态码
     */
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private final int code;
    /**
     * 错误原因
     */
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private final String message;
    /**
     * 响应结果
     */
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private final T data;

    public WebResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> WebResult<T> error(int code, String message) {
        return new WebResult<>(code, message, null);
    }

    public static <T> WebResult<T> error(String message) {
        return new WebResult<>(ResultCode.SERVER_ERROR.getCode(), message, null);
    }

    /**
     * 操作成功(无需返回数据)
     */
    public static <T> WebResult<T> success() {
        return new WebResult<>(ResultCode.WEB_RESULT_SUCCESS.getCode(), null, null);
    }

    /**
     * 操作成功, 返回数据
     */
    public static <T> WebResult<T> success(T result) {
        return new WebResult<>(ResultCode.WEB_RESULT_SUCCESS.getCode(), ResultCode.WEB_RESULT_SUCCESS.getMsg(), result);
    }

    /**
     * 分页返回
     */
    public static <T> WebResult<List<T>> page(PageResponse<T> pageResponse, List<T> dataList) {
        return new PageResult<>(pageResponse, dataList);
    }

    /**
     * 分页返回(数据列表从pageResult取)
     * public static <T> WebResult<List<T>> page(PageResponse<T> pageResponse) {
     * return new PageResult<>(pageResponse, pageResponse.getList());
     * }
     */

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
